<template>
  <div class="box">
    <!-- <el-card>
    <el-row :gutter="20">
      <el-col :span="24">
      </el-col>
    </el-row>
    </el-card>-->
    <el-card style="width: 100%; over-flow: scroll">
      <div slot="header" class="clearfix">
        <span>首页轮播图</span>
      </div>

      <div class="listBox">
        <el-card
          v-for="(item, index) in list"
          :key="index"
          style="margin-right: 5px; margin-top: 10px"
          @mouseenter="mouseenter(item)"
          @mouseleave="mouseleave"
        >
          <div class="mycard">
            <img
              style="width: 100%; height: 100%"
              :src="item.newurl"
              alt=""
              srcset=""
            />
            <div class="delBox" @click="delClick(item)">
              <img class="delImg" src="./del.png" alt="" srcset="" />
              <!-- <el-button size="mini" type="danger" @click="delClick(item)"
              >删除</el-button
            > -->
            </div>
          </div>
        </el-card>
        <div style="width: 384px; margin-right: 5px; margin-top: 10px">
          <div class="btnUpload" @click="formShow()">
            <img class="uploadImg" src="./upload.png" alt="" srcset="" />
          </div>
        </div>
      </div>
    </el-card>
    <el-dialog
      :title="contentAddForm.id ? '编辑' : '新增'"
      :visible.sync="dialogFormVisible"
    >
      <el-upload
        class="imgBox"
        :limit="1"
        action="https://jsonplaceholder.typicode.com/posts/"
        :file-list="fileList"
        :before-upload="beforePicUpload"
        list-type="picture-card"
        :http-request="handleUploadImg"
        :on-remove="handleRemove"
      >
        <i class="el-icon-plus" />
      </el-upload>
      <div style="color: red">
        <p>上传图片只能是jpg或者png格式!</p>
        <p>上传图片大小不能超过2MB!</p>
        <p>上传图片长宽需为1920*500！!</p>
      </div>
      <div slot="footer" class="dialog-footer">
        <el-button @click="cancelClick('contentAddForm')">取 消</el-button>
        <el-button type="primary" @click="submitForm('contentAddForm')"
          >确 定</el-button
        >
      </div>
    </el-dialog>
  </div>
</template>
<script>
import Oss from '@/utils/oss'
import { addWebImage, updateWebImage, listWebImage } from './api/index'

export default {
  data() {
    return {
      showCode: false,
      fileList: [],
      oss: {},
      dialogFormVisible: false,
      list: [],
      contentAddForm: {},
      imgurl: '',
      loading: true,
      stsToken: {
        accessKeyId: 'LTAI5tCQiELrNuXxFdf5wyuB',
        accessKeySecret: 'VlsN1KXHj4RV709wAOIHOnzjn9Qbke',
        bucket: 'utopia9527',
        region: 'oss-cn-shanghai'
      },
      mouseId: ''
    }
  },
  created() {
    this.oss = new Oss(this.stsToken, window)
    this.oss.__init__()
    setTimeout(() => {
      this.getList()
    }, 2000)
  },
  methods: {
    mouseenter(item) {
      this.mouseId = item.id
    },
    mouseleave() {
      this.mouseId = ''
    },
    cancelClick() {
      this.fileList = []
      this.imgurl = ''
      this.dialogFormVisible = false
    },
    handleClick(item) {
      this.dialogFormVisible = true
      this.fileList = [{ url: item.newurl }]
    },
    formShow() {
      this.fileList = []
      this.imgurl = ''
      this.dialogFormVisible = true
    },
    delClick(item) {
      // this.$confirm('此操作将永久删除该文件, 是否继续?', '提示', {
      //   confirmButtonText: '确定',
      //   cancelButtonText: '取消',
      //   type: 'warning'
      // })
      this.$alert(
        `<div> <img style="width:192px;height:50px;" src="${item.newurl}"></img></div>`,
        '确认删除此照片',
        {
          dangerouslyUseHTMLString: true
        }
      )
        .then(() => {
          updateWebImage({
            id: item.id,
            state: 2
          }).then((res) => {
            if (res.code === 1) {
              this.getList()
              this.$message({
                type: 'success',
                message: '删除成功!'
              })
            }
          })
        })
        .catch(() => {
          this.$message({
            type: 'info',
            message: '已取消删除'
          })
        })
    },
    getList() {
      this.loading = true
      // const ossConfig = {
      //   expires: 3600,
      //   process: 'image/auto-orient,1/quality,q_90/format,src'
      // }
      listWebImage({
        type: 2,
        state: 1
      }).then((res) => {
        if (res.obj) {
          this.list = res.obj.data.map((item) => {
            return Object.assign({}, item, {
              newurl: item.url
              // newurl: this.oss.__main__(item.url, 'readImg', ossConfig)
            })
          })
        }

        this.loading = false
        console.log(this.list)
      })
    },
    submitForm() {
      // type // 1logo  2轮播
      // stete //1 zhengchang  2 shanchu
      if (this.imgurl) {
        addWebImage({
          type: 2,
          url: this.imgurl
        }).then((res) => {
          if (res.code === 1) {
            this.dialogFormVisible = false
            this.$message.success('新增成功')
            this.imgurl = ''
            this.getList()
          } else {
            this.$message.error(res.msg)
          }
          console.log(res)
        })
      } else {
        this.$message.error('图片上传中，稍后再确认')
      }
    },
    beforePicUpload(file) {
      const _this = this
      const isJPG = file.type === 'image/jpeg' || 'image/png'
      const isLt2M = file.size / 1024 / 1024 < 2
      if (!isJPG) {
        // this.$Mint.Toast(')
        _this.$message.error({
          message: '上传图片只能是jpg或者png格式!'
        })
      }
      if (!isLt2M) {
        // this.$Mint.Toast('')
        _this.$message.error({
          message: '上传图片大小不能超过2MB!'
        })
      }

      // const isSize = new Promise(function (resolve, reject) {
      //   const width = 1920
      //   const height = 500
      //   const _URL = window.URL || window.webkitURL
      //   const img = new Image()
      //   img.onload = function () {
      //     const valid = img.width === width && img.height === height
      //     valid ? resolve() : reject()
      //   }
      //   img.src = _URL.createObjectURL(file)
      // }).then(
      //   () => {
      //     return file
      //   },
      //   () => {
      //     _this.$message.error({
      //       message: '上传图片长宽需为1920*500！!'
      //     })
      //     return Promise.reject()
      //   }
      // )
      return isJPG && isLt2M
    },

    handleUploadImg(param) {
      console.log(param)
      this.oss.__main__('activity', 'uploadImg', param).then((res) => {
        if (res.res.status === 200) {
          this.$message.success('上传成功')
          console.log(res.res.requestUrls)
          this.imgurl = res.res.requestUrls[0].split('?uploadId=')[0]
          // this.contentAddForm.image = res.name
          // this.fileList = [
          //   {
          //     name: 'food.jpeg',
          //     url: res.name
          //   }
          // ]
        }
      })
    },
    handleRemove(file, fileList) {
      console.log(file, fileList)
    }
    // handlePreview(file) {
    //   console.log(file)
    // },
    // delImg(item) {
    //   const arr = []
    //   this.fileList.map((res) => {
    //     if (res.name !== item.name) {
    //       console.log(item.name, res.name)
    //       arr.push(res)
    //     }
    //     console.log(arr, '')
    //     this.fileList = arr
    //   })
    // },
    // visible: function (item) {
    //   this.fileList.map((res) => {
    //     if (res.name === item.name) {
    //       res.showCode = true
    //     }
    //   })
    // },
    // invisible: function () {
    //   this.fileList.map((res) => {
    //     res.showCode = false
    //   })
    // }
  }
}
</script>
<style scoped>
>>> .el-card__body {
  padding: 10px;
}
.delImg {
  width: 20px;
  height: 20px;
}
.delBox {
  position: absolute;
  top: 0;
  right: 0;
  width: 30px;
  height: 30px;
  background: #fdfdff;
  display: flex;
  align-items: center;
  justify-content: center;
}
.uploadImg {
  width: 60px;
  height: 60px;
  display: flex;
  justify-content: center;
}
.btnUpload {
  margin-left: 142px;
  width: 100px;
  height: 100px;
  position: relative;
  display: flex;
  align-items: center;
  justify-content: center;
  flex-direction: column;
  border: 1px dashed #c0ccda;
  box-shadow: 0 2px 12px 0 rgb(0 0 0 / 10%);
  background: #fdfdff96;
  border-radius: 6px;
  padding: 10px;
}
.listBox {
  display: flex;
  align-items: center;
  flex-wrap: wrap;
}
.mycard {
  width: 384px;
  height: 100px;
  text-align: center;
  position: relative;
}
.box {
  width: 100%;
  display: flex;
  align-items: center;
  /* justify-content: center; */
}
.imgList {
  margin-top: 20px;
}
.imgItem {
  position: relative;
  width: 200px;
  height: 200px;
}
.imgItem img {
  width: 200px;
  height: 200px;
}
.delIcon {
  position: absolute;
  width: 20px;
  height: 20px;
  color: #333333;
  line-height: 20px;
  text-align: center;
  background: #f2f2f2;
}
</style>

